package com.glc.hms.system.controller.web;

import com.glc.hms.common.controller.BaseController;
import com.glc.hms.common.util.FileResolver;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件上传
 *
 * @author ljt
 * @since 2019-11-27 22:55
 */
@Slf4j
@Api(value = "文件上传", description = "文件上传接口", basePath = "/webApi/file")
@RestController
@RequestMapping("/webApi/file")
public class FileController extends BaseController {

    @Autowired
    private FileResolver fileResolver;

    @ApiOperation(value = "上传文件", response = FileResolver.FileProtocol.class)
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public Object uploadFile(@RequestBody MultipartFile uploadFile) throws IOException {
        File tmp = new File((fileResolver.getTmpPath()));
        if(!tmp.exists()){
            tmp.mkdirs();
        }

        String fileName = uploadFile.getOriginalFilename();
        File tmpFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), uploadFile.getName(), tmp);
        uploadFile.transferTo(tmpFile);

        FileResolver.FileProtocol fileProtocol = fileResolver.new FileProtocol();
        fileProtocol.setFile(tmpFile);
        fileProtocol.setFileName(fileName);

        return fileResolver.saveFile(fileProtocol);
    }
}
